﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Village : MonoBehaviour
{

	public List<AudioClip> SonsVillage = new List<AudioClip>();
	private int lastLevel = -100;
	private List<Vector3> buildingsPosition = new List<Vector3> ();
	private List<Quaternion> buildingsRotation = new List<Quaternion> ();

	Animator[] animators;

	public void Awake()
	{
		animators = GetComponentsInChildren<Animator>();
		Transform[] tmp = GetComponentsInChildren<Transform>();
		for (int i = 0; i < tmp.Length; i++)
		{
			if (tmp[i].parent == this.transform)
			{
				buildingsPosition.Add (tmp[i].localPosition);
				buildingsRotation.Add (tmp[i].localRotation);
			}
		}
	}

	public void ChangeLevel(int newLevel)
	{
		for (int i = 0; i < animators.Length; i++)
		{
			int level = animators[i].GetInteger("Level");
			if (level + 1 < newLevel)
			{
				animators[i].SetInteger ("Level", level + 1);
				StartCoroutine ("AddLevel", newLevel);
			}
			else if (level - 1 > newLevel)
			{
				animators[i].SetInteger ("Level", level - 1);
				StartCoroutine ("AddLevel", newLevel);
			}
			else
				animators[i].SetInteger("Level", newLevel);
		}

		// Play sound

		if(this.lastLevel != newLevel){
			this.audio.clip = this.SonsVillage[Random.Range(0, this.SonsVillage.Count)];
			this.audio.Play();

			this.lastLevel = newLevel;
		}

	}

	public IEnumerator AddLevel(int newLevel)
	{
		yield return new WaitForSeconds (0.1f);
		for (int i = 0; i < animators.Length; i++)
			animators [i].SetInteger ("Level", newLevel);
	}

	public void Reset()
	{
		for (int i = 0; i < animators.Length; i++)
		{
			animators [i].SetInteger ("Level", 0);
			animators[i].SetTrigger("Reset");
		}

		List<Vector3> tmp = new List<Vector3> (buildingsPosition);
		Transform[] childrenTransform = GetComponentsInChildren<Transform>();
		for (int i = 0; i < childrenTransform.Length; i++)
		{
			if (childrenTransform[i].parent == this.transform)
			{
				int rdm;
				if (tmp.Count > 0)
					rdm = Random.Range(0, tmp.Count);
				else
					rdm = 0;

				childrenTransform [i].localPosition = new Vector3 (tmp[rdm].x, childrenTransform [i].localPosition.y, tmp[rdm].z);
				childrenTransform[i].localRotation = buildingsRotation[rdm];
				tmp.RemoveAt(rdm);
			}
		}
	}
}
